package com.loe.view.viewpager;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

import java.util.ArrayList;
import java.util.List;

public class LoeSlideMoreViewPager extends ViewPager
{
    private List<FragTabItem> items;
    private FragmentManager fragmentManager;
    private FragAdapter pagerAdapter;

    public int index = 0;

    /**
     * 是否可滑动
     */
    private boolean canMove = true;

    public LoeSlideMoreViewPager(Context context)
    {
        super(context);
    }

    public LoeSlideMoreViewPager(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public void init(FragmentManager fragmentManager, ArrayList<FragTabItem> items)
    {
        this.items = items;
        List<Fragment> fragments = fragmentManager.getFragments();
        if (fragments.size() == items.size())
        {
            for (int i = 0; i < fragments.size(); i++)
            {
                this.items.get(i).fragment = fragments.get(i);
            }
        }
        this.fragmentManager = fragmentManager;

        // 初始化ViewPager
        initPager();

    }
    /**
     * 初始化ViewPager及监听事件
     */
    private void initPager()
    {
        pagerAdapter = new FragAdapter(fragmentManager, items);
        setAdapter(pagerAdapter);
        // 设置切换效果
        //setPageTransformer(true, new RotatePageTransformer());
        // 设置缓存视图个数
        setOffscreenPageLimit(items.size() - 1);
    }

    public FragTabItem get(int index)
    {
        return items.get(index);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev)
    {
        if (canMove)
        {
            return super.onInterceptTouchEvent(ev);
        }
        else
        {
            return false;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev)
    {
        if (canMove)
        {
            return super.onTouchEvent(ev);
        }
        else
        {
            return false;
        }
    }

    public Fragment getNowFragment()
    {
        return get(index).fragment;
    }

    /**
     * 设置是否可滑动
     */
    public void setCanMove(boolean canMove)
    {
        this.canMove = canMove;
    }

    public int dp_px(float dpValue)
    {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}